<template>
    <div>
        <!-- 面包屑导航区 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图区 --> 
        <el-card class=" ">
            <!-- 搜索与添加区 -->
            <el-row :gutter="20">
                <el-col :span="9">
                    <el-input 
                        placeholder="请输入内容"
                        v-model="queryInfo.query"
                        clearable
                        @clear="getUserList"
                    >
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>
            <!-- 用户列表区域 -->
            <el-table
                :data="userList"
                style="width: 100%"
                border
            >
                <el-table-column 
                    type="index"
                    label="#"
                >
                </el-table-column>
                <el-table-column
                    prop="username"
                    label="姓名"
                >
                </el-table-column>
                <el-table-column
                    prop="email"
                    label="邮箱"
                >
                </el-table-column>
                <el-table-column
                    prop="mobile"
                    label="电话"
                >
                </el-table-column>
                <el-table-column
                    prop="role_name"
                    label="角色"
                >
                </el-table-column>
                <el-table-column
                    label="状态"
                >
                    <template slot-scope="scope">
                        <el-switch
                            v-model="scope.row.mg_state"
                            @change="userStateChange(scope.row)"
                        >
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column
                    label="操作"
                >   
                    <!-- 作用域插槽 -->
                    <template slot-scope="scope">
                        <!-- 编辑用户信息 -->
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)">
                        </el-button>
                        <!-- 删除用户 -->
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)"></el-button>
                        <!-- 按钮提示信息 -->
                        <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
                            <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页区 -->
            <el-pagination  
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="[10]"
                :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
            >
            </el-pagination>
            <!-- dialog -->
            <el-dialog
                title="添加用户"
                :visible.sync="addDialogVisible"
                width="50%"
                @close="addDialogColsed"
                
            >
                <el-form :model="addForm" :rules="addFormRules" ref="addFromRef" label-width="70px">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="addForm.username"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input v-model="addForm.password"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="addForm.email"></el-input>
                    </el-form-item>
                    <el-form-item label="手机" prop="mobile">
                        <el-input v-model="addForm.mobile"></el-input>
                    </el-form-item>
                </el-form>

                <span slot="footer" class="dialog-footer">
                    <el-button @click="addDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addUser">确 定</el-button>
                </span>
            </el-dialog>
            <!-- 修改用户信息对话框 -->
            <el-dialog
                title="修改用户信息"
                :visible.sync="editDialogVisable"
                width="50%"
                @close="editDialogClosed"
            >
                <el-form ref="editFormRef" :model="editForm" label-width="70px" :rules="editFormRules">
                    <el-form-item label="用户名">
                        <el-input v-model="editForm.username" disabled></el-input>
                    </el-form-item>
                     <el-form-item label="邮箱" prop="email">
                        <el-input v-model="editForm.email"></el-input>
                    </el-form-item>
                     <el-form-item label="手机" prop="mobile">
                        <el-input v-model="editForm.mobile"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="editDialogVisable = false">取 消</el-button>
                    <el-button type="primary" @click="editUserInfo">确 定</el-button>
                </span>
            </el-dialog>

            
        </el-card>
    </div>
</template>

<script>
    export default {
        data() {
            var checkMobile = (rule, value, callback) => {
                const regMobile = /^1[3456789]\d{9}$/
                    if (regMobile.test(value)){
                        return callback()
                    }
                    callback(new Error("请输入合法手机号"))
            }
            return {
                queryInfo: {
                    query: '',
                    pagenum: 1,
                    pagesize: 10
                },
                userList:[],
                total:0,
                // 控制dialog对话框的显示与隐藏，默认false
                addDialogVisible: false,
                addForm:{
                    username:'',
                    password:'',
                    email:'',
                    mobile:''
                },
                addFormRules:{
                    username:[ { required: true, message: '请输入用户名', trigger: 'blur' },],
                    password:[ { required: true, message: '请输入密码', trigger: 'blur' },],
                    email:[ 
                            { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                            { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
                        ],
                    mobile:[ 
                        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                        { validator: checkMobile, trigger: 'blur' }
                        ]
                },
                editDialogVisable: false,
                editForm:{},
                editFormRules:{
                    email:[ 
                        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
                    ],
                    mobile:[ 
                        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                        { validator: checkMobile, trigger: 'blur' }
                    ]
                }
            }
        },
        created () {
            this.getUserList();
        },
        methods: {
            async getUserList() {
                const {data: res} = await this.$http.get('users',{params:this.queryInfo})
                if(res.meta.status !== 200){
                    return this.$message.err(res.meta.msg)
                }else{                    
                    this.userList = res.data.users                                                    
                    this.total = res.data.total
                }
            },
            handleSizeChange(val){
                // console.log(val);
                this.queryInfo.pagesize = val
                this.getUserList()
            },
            handleCurrentChange(val){
                // console.log(val);
                this.queryInfo.pagenum = val
                this.getUserList()
            },
            // 监听switch状态改变
            async userStateChange(userInfo){
                const {data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
                if(res.meta.status !== 200){
                    userInfo.mg_state = !userInfo.mg_state
                    return this.$message.err("修改状态失败")
                }else{
                    return this.$message.success("修改状态成功")
                }
            },
            // 监听关闭对话框关闭事件
            addDialogColsed(){
                this.$refs.addFromRef.resetFields()
            },
            // 点击按钮，添加新用户
            addUser(){
                this.$refs.addFromRef.validate(async valid => {
                    if(!valid) return
                    // 预校验通过，发送网络请求;
                   const{data: res} =  await this.$http.post("users",this.addForm)
                   if(res.meta.status !== 201){
                       this.$message.error("添加用户失败")
                   }else{
                       this.$message.success("添加用户成功")
                       this.addDialogVisible = false
                       this.getUserList()
                   }
                })
            },
            async showEditDialog(id){                
                this.editDialogVisable = true
                const {data: res} = await this.$http.get("users/" + id)
                if(res.meta.status !== 200){
                    return this.$message.error("查询用户失败")
                }else{
                    this.editForm = res.data
                }
            },
            editDialogClosed(){
                this.$refs.editFormRef.resetFields()
            },
            editUserInfo(){
                this.$refs.editFormRef.validate( async valid => {
                    console.log(valid);
                    if (!valid) return 
                    const {data: res} = await this.$http.put("users/" + this.editForm.id,{email: this.editForm.email, mobile: this.editForm.mobile})
                    if(res.meta.status !== 200){
                        return this.$message.error("修改信息失败")
                    }else{
                        this.editDialogVisable = false
                        this.getUserList()
                        return this.$message.success("修改信息成功")
                    }
                    
                })
            },
            async removeUserById(id){
                const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(
                err => err
            )
            if(confirmResult !== 'confirm'){
                return this.$message.info("取消删除")
            }else{
                const {data: res} = await this.$http.delete("users/" + id)
                if(res.meta.status !== 200){
                    this.$message.error("删除失败")
                }else{
                    this.getUserList()
                    this.$message.success("成功删除")
                }
            }   
        }
    }
}
</script>

<style lang="less" scoped>

</style>